package com.rainng.coursesystem.service.admin;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rainng.coursesystem.controller.admin.vo.SysGroupReqDTO;
import com.rainng.coursesystem.controller.admin.vo.SysUserQueryReqDTO;
import com.rainng.coursesystem.controller.admin.vo.SysUserSaveReqDTO;
import com.rainng.coursesystem.manager.admin.AdminManager;
import com.rainng.coursesystem.manager.admin.StudentManager;
import com.rainng.coursesystem.manager.admin.TeacherManager;
import com.rainng.coursesystem.model.bo.LoginStatusBO;
import com.rainng.coursesystem.model.entity.*;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.service.BaseService;
import com.rainng.coursesystem.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AdminService extends BaseService {
    private final AdminManager manager;
    private final TeacherManager tmanager;
    private final StudentManager smanager;
    private final UserService service;


    public AdminService(AdminManager manager, UserService userService, TeacherManager tmanager, StudentManager smanager, UserService service) {
        this.manager = manager;
        this.tmanager = tmanager;
        this.smanager = smanager;
        this.service = service;
    }

    public ResultVO get(Integer id) {
        AdminEntity entity = manager.get(id);
        if (entity == null) {
            return failedResult("管理员Id: " + id + "不存在!");
        }
        entity.setPassword("");
        return result(entity);
    }

    public ResultVO update(AdminEntity entity) {
        AdminEntity originEntity = manager.get(entity.getId());
        if (originEntity == null) {
            return failedResult("管理员Id: " + entity.getId() + "不存在!");
        }

    //    if (entity.getPassword().equals("")) {
            entity.setPassword(originEntity.getPassword());
     //   } else {
     //       entity.setPassword(userService.computePasswordHash(entity.getPassword()));
      //  }


        manager.update(entity);
        return result("更新成功");
    }

    public ResultVO delete(Integer id) {
        if (manager.get(id) == null) {
            return failedResult("管理员Id: " + id + "不存在!");
        }
        manager.delete(id);
        return result("删除成功");
    }

    public ResultVO deleteUser(String id) {
        if (manager.getUser(id) == null) {
            return failedResult("管理员Id: " + id + "不存在!");
        }
        //关联删除业务
        RoleEntity entity = manager.getUser(id);
        String role = entity.getRole();
        String name = entity.getUserName();
        manager.deleteUser(id);
        if("3".equals(role)){
            manager.deleteByUserName(name);
        }
        if("2".equals(role)){
            tmanager.deleteByUserName(name);
        }
        if("1".equals(role)){
            smanager.deleteByUserName(name);
        }
        return result("删除成功");
    }


    public ResultVO deleteMultiUser(List<String> ids) {

        for(String id :ids){
            if (manager.getUser(id) == null) {
                //return failedResult("管理员Id: " + id + "不存在!");
                continue;
            }
            //关联删除业务
            RoleEntity entity = manager.getUser(id);
            String role = entity.getRole();
            String name = entity.getUserName();
            manager.deleteUser(id);
            if("3".equals(role)){
                manager.deleteByUserName(name);
            }
            if("2".equals(role)){
                tmanager.deleteByUserName(name);
            }
            if("1".equals(role)){
                smanager.deleteByUserName(name);
            }
            //return result("删除成功");
        }
        return result("删除成功");
    }



    public ResultVO create(AdminEntity entity) {
        if (manager.get(entity.getId()) != null) {
            return failedResult("管理员Id: " + entity.getId() + "已存在!");
        }

        manager.create(entity);
        return result("添加成功");
    }

    public ResultVO getUser(String id) {
        RoleEntity entity = manager.getUser(id);
        if (entity == null) {
            return failedResult("管理员Id: " + id + "不存在!");
        }
        entity.setPassword("");
        return result(entity);
    }


    //封装接口
    public ResultVO createUser(SysUserSaveReqDTO reqDTO) {
        if (StringUtils.isBlank(reqDTO.getRole())){
            return failedResult("角色为空");
        }
        QueryWrapper<RoleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RoleEntity::getUserName,reqDTO.getUserName());
        //新增
        RoleEntity user = new RoleEntity();
        BeanUtil.copyProperties(reqDTO, user);//第一个参数向第二个赋值
        if (StringUtils.isBlank(reqDTO.getId())){
            queryWrapper.lambda().eq(RoleEntity::getUserName,reqDTO.getUserName());
            long count = manager.countUser(queryWrapper);
            if (count > 0){
                return failedResult("登录名不能重复");
            }
            String id = IdWorker.getIdStr();
            if (StringUtils.isBlank(reqDTO.getId())){
                user.setCreateBy("admin");
                user.setId(id);
                user.setCreateTime(new Date());
            }
            if("7".equals(reqDTO.getRole())){
                user.setCompanyName(reqDTO.getCompanyName());
            }

            user.setPassword(reqDTO.getPassword());
            user.setRole(reqDTO.getRole());
            user.setRoleId(reqDTO.getRole());
            manager.createUser(user);
            if("3".equals(reqDTO.getRole())){
                AdminEntity adminEntity = new AdminEntity();
                adminEntity.setPassword(reqDTO.getPassword());
                adminEntity.setUsername(reqDTO.getUserName());
                adminEntity.setPrivilege(255);
                manager.create(adminEntity);
            }
            if("2".equals(reqDTO.getRole())){
                TeacherEntity tEntity = new TeacherEntity();
                tEntity.setPassword(reqDTO.getPassword());
                tEntity.setName(reqDTO.getUserName());
                tEntity.setNumber(reqDTO.getUserName());
                tEntity.setDepartmentId(1);
                tmanager.create(tEntity);
            }
            if("1".equals(reqDTO.getRole())){
                StudentEntity sEntity = new StudentEntity();
                sEntity.setPassword(reqDTO.getPassword());
                sEntity.setName(reqDTO.getUserName());
                sEntity.setNumber(reqDTO.getUserName());
                sEntity.setClassId(1);
                sEntity.setSex(1);
                smanager.create(sEntity);
            }
            return result("添加成功");
        }
        //修改业务
        List<RoleEntity> roleEntityList = manager.selectAllUsers(queryWrapper);
        if(roleEntityList.size() == 0){
            return failedResult("角色名不存在");
        }
        String roleBefore = roleEntityList.get(0).getRole();
        //String pwdBefore = roleEntityList.get(0).getPassword();

        //Boolean pwdsame = pwdBefore.equals(reqDTO.getPassword());
        Boolean rolesame = roleBefore.equals(reqDTO.getRole());
        user.setRoleId(user.getRole());
        manager.updateUser(user);
        if(rolesame){
            return result("修改成功");
        }

        if("3".equals(reqDTO.getRole())){
            AdminEntity adminEntity = new AdminEntity();
            adminEntity.setPassword(reqDTO.getPassword());
            adminEntity.setUsername(reqDTO.getUserName());
            adminEntity.setPrivilege(255);
            manager.create(adminEntity);
        }
        if("2".equals(reqDTO.getRole())){
            TeacherEntity tEntity = new TeacherEntity();
            tEntity.setPassword(reqDTO.getPassword());
            tEntity.setName(reqDTO.getUserName());
            tEntity.setNumber(reqDTO.getUserName());
            tEntity.setDepartmentId(1);
            tmanager.create(tEntity);
        }
        if("1".equals(reqDTO.getRole())){
            StudentEntity sEntity = new StudentEntity();
            sEntity.setPassword(reqDTO.getPassword());
            sEntity.setName(reqDTO.getUserName());
            sEntity.setNumber(reqDTO.getUserName());
            sEntity.setClassId(1);
            sEntity.setSex(1);
            smanager.create(sEntity);
        }
        //删除原有的
        if("3".equals(roleBefore)){
            manager.deleteByUserName(reqDTO.getUserName());
        }
        if("2".equals(roleBefore)){
            tmanager.deleteByUserName(reqDTO.getUserName());
        }
        if("1".equals(roleBefore)){
            smanager.deleteByUserName(reqDTO.getUserName());
        }

        return result("修改成功");
    }

//    public void save(SysUserSaveReqDTO reqDTO) {
//        if (StringUtils.isBlank(reqDTO.getRoleId())){
//            throw new ServiceException("角色为空");
//        }
//        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(SysUser::getUserName,reqDTO.getUserName());
//        if (!StringUtils.isBlank(reqDTO.getId())){
//            queryWrapper.lambda().ne(SysUser::getId,reqDTO.getId());
//        }
//        int count = this.count(queryWrapper);
//        if (count > 0){
//            throw new ServiceException("登录名不能重复!");
//        }
//        SysUser user;
//        String id = IdWorker.getIdStr();
//        if (StringUtils.isBlank(reqDTO.getId())){
//            user = new SysUser();
//            BeanMapper.copy(reqDTO,user);
//            user.setCreateBy(getUserName());
//            user.setId(id);
//            user.setCreateTime(new Date());
//        }else {
//            user = this.getById(reqDTO.getId());
//            BeanMapper.copy(reqDTO,user);
//            user.setUpdateBy(getUserName());
//            user.setUpdateTime(new Date());
//        }
//        if(!StringUtils.isBlank(reqDTO.getPassword())){
//            PassInfo pass = PassHandler.buildPassword(reqDTO.getPassword());
//            user.setPassword(pass.getPassword());
//            user.setSalt(pass.getSalt());
//        }
//        //更新用户表
//        this.saveOrUpdate(user);
//    }


    public ResultVO list() {
        return result(manager.list());
    }


    public ResultVO showList(SysUserQueryReqDTO po) {
        ResultVO vo = service.getLoginStatus();
        LoginStatusBO m = (LoginStatusBO)vo.getData();
        Integer userType = m.getUserType();
        String userName = m.getUsername();
        if(userType != 3){
            po.setUserName(userName);
        }
        return result(manager.showRolelist(po));
    }

    public ResultVO getTotal(SysUserQueryReqDTO po) {
        ResultVO vo = service.getLoginStatus();
        LoginStatusBO m = (LoginStatusBO)vo.getData();
        Integer userType = m.getUserType();
        String userName = m.getUsername();
        if(userType != 3){
            po.setUserName(userName);
        }
        return result(manager.getRoleCount(po));
    }


    public ResultVO getListById(String id) {
        return result(manager.getUser(id));
    }

    public ResultVO getUserByRoleId() {

        String groupid = null;
        ResultVO vo = service.getLoginStatus();
        LoginStatusBO m = (LoginStatusBO)vo.getData();
        Integer userType = m.getUserType();
        String userName = m.getUsername();
        if(userName != null && userType != 3 && userType != 4){
            groupid =manager.getGroupIdByUserName(userName);
        }
        if(userName != null && userType != 5 && userType != 6 && userType != 7) {
            groupid = "1688826189812711425";

        }

        return result(manager.getUserByGroupId(groupid));

    }



    public ResultVO getAllRoles(){
        return result(manager.getAllUserRoles());
    }

    public ResultVO deleteGroups(List<String> ids){
        return result(manager.deleteGroups(ids));
    }

    public ResultVO getGroupById(String id){
        UserGroupEntity obj = manager.getGroupById(id);
        return result(obj);
    }

    public ResultVO getGroups(SysGroupReqDTO reqDTO){
        return result(manager.showUserGrouplist(reqDTO));
    }

    public ResultVO getAllGroups(){
        return result(manager.showAllUserGrouplist());
    }

    public ResultVO getGroupsCount(SysGroupReqDTO reqDTO){
        return result(manager.showUserGroupCount(reqDTO));
    }


    public ResultVO saveGroup(SysGroupReqDTO input){
        UserGroupEntity group = new UserGroupEntity();
        BeanUtil.copyProperties(input,group);
        //新增
        if (StringUtils.isBlank(group.getId())){
            group.setId(IdWorker.getIdStr());
            ResultVO auth = service.getLoginStatus();
            log.info(auth.toString());
            String name = "admin";
            group.setCreateBy(name);
            //检查组别是否重名
            boolean b = checkGroupName(group.getGroupName());
            if (b){
                return failedResult("不能为同名");
            }
            int i = manager.saveUserGroup(group);
            return result("新增成功");
        }
        //判断名称是否修改
        UserGroupEntity before = manager.getGroupById(group.getId());
        if(before == null){
            return result("id错误");
        }
        //修改
        if(!before.getGroupName().equals(input.getGroupName())){
            boolean c = checkGroupName(input.getGroupName());
            if (c){
                return failedResult("新增不能为同名");
            }
        }
        //String name = sysUserService.getUserName();
        //group.setUpdateBy(name);
        group.setUpdateBy("admin");
        int j = manager.updateUserGroup(group);

        return result("修改成功");
    }


    /**
     * 校验组名是否重复
     * @param groupName
     * @return
     */
    private boolean checkGroupName(String groupName) {
        QueryWrapper<UserGroupEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserGroupEntity::getGroupName,groupName);
        long count = manager.countGroups(queryWrapper);
        log.info("同名组别数量为");

        if (count > 0){
            return true;
        }
        return false;

    }

}
